import { isFunction, isString } from "lodash";

// 定义一些类型别名来描述传递的对象结构
type EventFunction = (value: any, maformObj: any) => Promise<any> | any;
type Component = Record<string, any>; // 具体类型根据实际组件的结构进行调整
type MaFormObject = Record<string, any>; // 具体类型根据实际表单对象结构进行调整

export const runEvent = async (component: Component, evName: string, maformObj: MaFormObject, value?: any): Promise<any> => {
  return value ? await haveArgsEvent(component, value, evName, maformObj) : await notHaveArgsEvent(component, evName, maformObj);
};

export const haveArgsEvent = async (component: Component, value: any, evName: string, maformObj: MaFormObject): Promise<any> => {
  if (component[evName]) {
    if (isFunction(component[evName])) {
      return await (component[evName] as EventFunction)(value, maformObj);
    }
    if (isString(component[evName])) {
      const customFn = new Function("value", "maFormObject", component[evName]) as EventFunction;
      return await customFn.call(component, value, maformObj);
    }
  }
};

export const notHaveArgsEvent = async (component: Component, evName: string, maformObj: MaFormObject): Promise<any> => {
  if (component[evName]) {
    if (isFunction(component[evName])) {
      return await (component[evName] as (maformObj: MaFormObject) => Promise<any> | any)(maformObj);
    }
    if (isString(component[evName])) {
      const customFn = new Function("maFormObject", component[evName]) as (maformObj: MaFormObject) => Promise<any> | any;
      return await customFn.call(component[evName], maformObj);
    }
  }
};

export const tabAddEvent = async (component: Component, maformObj: MaFormObject): Promise<void> => {
  await haveArgsEvent(component, component?.tabs, "onTabAdd", maformObj);
};

export const tabDeleteEvent = async (component: Component, value: any, maformObj: MaFormObject): Promise<void> => {
  await haveArgsEvent(component, { tabs: component?.tabs, value }, "onTabDelete", maformObj);
};
